﻿using AutoMapper;
using BasicInformation.ApiWrite.Application.Command.Device;
using BasicInformation.Domain;
using BasicInformation.ErrorCode;
using BasicInformation.Infrastructure.Implement;
using BasicInformation.Infrastructure.Interface;
using MediatR;

namespace BasicInformation.ApiWrite.Application.Handler.Device
{
    /// <summary>
    /// 设备管理添加处理类
    /// </summary>
    public class AddDeviceHandler : IRequestHandler<AddDeviceCommand, ApiResult<int>>
    {
        private readonly IMapper mapper;
        private readonly ILogger<AddDeviceHandler> logger;
        private readonly DatabaseContext db;

        public AddDeviceHandler(IMapper mapper, ILogger<AddDeviceHandler> logger, DatabaseContext db)
        {
            this.mapper = mapper;
            this.logger = logger;
            this.db = db;
        }
        public async Task<ApiResult<int>> Handle(AddDeviceCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            var res=mapper.Map<DeviceModel>(request);
            var model = db.SqlSugar.Queryable<DeviceModel>().Where(x => x.DeviceCode == request.DeviceCode&&x.DeviceName==request.DeviceName).Count();
            if (model > 0)
            {
                result.Msg = "该设备管理已存在，请重新输入";
                result.Code = ApiEnum.Fail;
                logger.LogError(result.Msg);
                return await Task.FromResult(result);
            }
            int r= await db.SqlSugar.Insertable(res).ExecuteReturnIdentityAsync();
            if (r > 0)
            {
                result.Msg = "设备管理添加成功";
                result.Data = r;
                result.Code = ApiEnum.OK;
                logger.LogInformation(result.Msg);
            }
            else
            {
                result.Msg = "设备管理添加失败";
                result.Data = r;
                result.Code = ApiEnum.Fail;
                logger.LogError(result.Msg);
            }
            return await Task.FromResult(result);
        }
    }
}
